<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="back" @click="navigateBack">
				<uni-icons type="left" size="20"></uni-icons>
			</view>
			<view class="title">救援任务</view>
			<view class="right">
				<uni-icons type="more-filled" size="20"></uni-icons>
			</view>
		</view>

		<!-- 标签页 -->
		<view class="bg">
		</view>
		<view class="tabs">
			<view class="tab-item" :class="{ active: currentTab === 0 }" @click="switchTab(0)">求助中</view>
			<view class="tab-item" :class="{ active: currentTab === 1 }" @click="switchTab(1)">已接单</view>
			<view class="tab-item" :class="{ active: currentTab === 2 }" @click="switchTab(2)">超时</view>
		</view>

		<!-- 筛选区域 -->
		<view class="filter-section">
			<view class="filter-item">
				<text>总条数：{{helptaskList.length}}</text>
				<text>救援类型:</text>
				<uni-data-select v-model="helpType" :localdata="helpTypes" placeholder="全部"
					@change="handleHelpTypeChange"></uni-data-select>
			</view>

		</view>

		<!-- 订单列表 -->
		<view class="order-list">
			<view class="order-item" style="text-align: center;" v-if="helptaskList.length==0">
				暂无数据
			</view>
			<view class="order-item" v-for="(item, index) in helptaskList" :key="item.id">
				<view class="order-info">
					<view class="info-row">
						<text class="label">救援单号:</text>
						<text class="value">{{ item.id }}</text>
						<!-- 	<view>{{item.status}}</view> -->
						<view :style="{
						  color: item.status === 0 ? '#1890ff' : 
								item.status === 1 ? '#52c41a' : '#faad14',
						  fontSize: '14px'
						}">
							{{
						  item.status === 0 ? '求助中' : 
						  item.status === 1 ? '已接单' : '超时' 
						}}
						</view>
					</view>
					<view class="info-row">
						<text class="label">救援类型:</text>
						<text class="value">{{ item.typeId === 1 ? '搭电' : 
						  item.typeId === 2 ? '换胎' : '拖车' }}</text>
					</view>
					<view class="info-row">
						<text class="label">预约日期:</text>
						<text class="value">{{ item.time }}</text>
						<view style="background-color: #557AD6; color: white;padding: 1px 5px;border-radius: 5px;"
							@click="toDetail(item.id)" v-if="item.status === 1">查看详情</view>
						<view style="background-color: #40b782; color: white;padding: 1px 5px;border-radius: 5px;"
							@click="toReceive(item.id)" v-if="item.status === 0">我要接单</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,reactive
	} from 'vue';
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import request from '../../../utils/request.js'

	onLoad(() => {
		//getInfo()
		gethelpInfo()
		// 添加刷新监听
		uni.$on('refreshPage', () => {
			gethelpInfo()
		})
	})
	onUnload(() => {
		uni.$off('refreshPage')
	})

	// 获取店铺id信息
	function getInfo() {
		const Info = uni.getStorageSync('info');
		queryParams.value.mid = Info.mid
	}

	function toDetail(id) {
		uni.navigateTo({
			url: '/pages/index/jiuyuanrenwu/jiuyuanxiangqing/jiuyuanxiangqing?id=' + id
		})
	}
	// 获取信息
	const queryParams = ref({
		pageNum: 1,
		pageSize: 10,
		uid: null,
		mid: null,
		typeId: null,
		status: 0
	})
	
	
	const helptaskList = ref([])
//救援信息列表
	function gethelpInfo() {
		if(queryParams.value.status != 0){
			getInfo()
		}
		request({
			url: 'yyq/helptask/list',
			method: 'GET',
			data: queryParams.value,
			success(res) {
				console.log(res.data.rows);
				helptaskList.value = res.data.rows;
			},
			fail(error) {
				console.error('获取救援信息失败', error);
				uni.showToast({
					title: '获取救援信息失败，请重试',
					icon: 'none'
				});
			}
		});
	}
	const hid = ref()
	const taskInfo = ref({})
	const form = reactive({
	  id: null,
	  uid: null,
	  mid: null,
	  time: null,
	  typeId: null,
	  position: null,
	  end: null,
	  name: null,
	  phone: null,
	  carNum: null,
	  carType: null,
	  description: null,
	  status: null,
	  deleted: null
	})
//商家接单
function toReceive(id) {
    uni.showModal({
        title: '确认接单',
        content: '是否确认接收此订单？',
        confirmText: '确认',
        cancelText: '取消',
        success: (res) => {
            if (!res.confirm) return; // 商家取消接单（救援任务）
            hid.value = id;

            // 根据id查询救援任务信息，赋值给form，以便后续更新救援任务
            request({
                url: 'yyq/helptask/' + hid.value,
                method: 'GET',
                success: (res) => {
                    console.log('信息', res.data.data);
                    taskInfo.value = res.data.data;

                    // 完善form信息
                    form.id = taskInfo.value.id;
                    form.uid = taskInfo.value.uid;
                    form.time = taskInfo.value.time;
                    form.typeId = taskInfo.value.typeId;
                    form.position = taskInfo.value.position;
                    form.name = taskInfo.value.name;
                    form.phone = taskInfo.value.phone;
                    form.carType = taskInfo.value.carType;
                    form.description = taskInfo.value.description;
                    form.deleted = taskInfo.value.deleted;

                    // 填入商家id，修改救援任务状态为已接单
                    const shop = uni.getStorageSync('info');
                    form.mid = shop.mid;
                    form.status = 1;

                    // 发起更新请求
                    request({
                        url: 'yyq/helptask',
                        method: 'PUT',
                        data: form,
                        success: (res) => {
                            console.log('修改', res.data);
                            // 处理成功响应
                            uni.showToast({
                                title: '操作成功',
                                icon: 'none'
                            });
                            // 触发刷新页面事件
                            uni.$emit('refreshPage');
                        },
                        fail: (error) => {
                            console.error('处理失败', error);
                            // 显示错误提示
                            uni.showToast({
                                title: '操作失败，请重试',
                                icon: 'none'
                            });
                        }
                    });
                },
                fail: (error) => {
                    console.error('获取救援任务信息失败', error);
                    // 显示错误提示
                    uni.showToast({
                        title: '获取救援任务信息失败，请重试',
                        icon: 'none'
                    });
                }
            });
        }
    });
}





	// 定义响应式数据
	const currentTab = ref(0);
	const helpType = ref('')
	const helpTypes = ref([{
			text: '全部',
			value: null
		},
		{
			text: '搭电',
			value: 1
		},
		{
			text: '换胎',
			value: 2
		},
		{
			text: '拖车',
			value: 3
		}
	]);


	// 定义方法
	const navigateBack = () => {
		uni.navigateBack();
	};
//跳转不同状态
	const switchTab = (index) => {
		currentTab.value = index;
		queryParams.value.status = index
		if (index != 1) {
			queryParams.value.mid = null;
		}
		gethelpInfo()
		// TODO: 根据tab切换加载不同状态的订单 
	};

	function handleHelpTypeChange(e) {
		queryParams.value.typeId = e // 更新查询参数
		gethelpInfo() // 重新查询数据
	}
</script>

<style lang="scss" scoped>
	.bg {
		width: 100%;
		height: 210rpx;
		background-color: #007aff;
	}

	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		height: 44px;
		background-color: #007AFF;
		color: #fff;
		padding: 0 15px;

		.back {
			width: 44px;
		}

		.title {
			flex: 1;
			text-align: center;
			font-size: 18px;
		}

		.right {
			width: 44px;
			text-align: right;
		}
	}

	.tabs {
		margin-left: 10px;
		margin-right: 10px;
		margin-top: -200rpx;
		border-top-right-radius: 20px;
		border-top-left-radius: 20px;
		display: flex;
		background-color: #fff;
		border-bottom: 1px solid #eee;

		.tab-item {
			flex: 1;
			height: 44px;
			line-height: 44px;
			text-align: center;
			font-size: 15px;
			color: #333;
			position: relative;

			&.active {
				color: #007AFF;

				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 20px;
					height: 2px;
					background-color: #007AFF;
				}
			}
		}
	}

	.filter-section {
		margin-left: 10px;
		margin-right: 10px;
		background-color: #fff;
		padding: 10px 15px;

		.filter-item {
			display: flex;
			align-items: center;
			margin-bottom: 10px;

			text {
				width: 80px;
				font-size: 14px;
				color: #333;
			}
		}
	}

	.order-list {
		padding: 10px;

		.order-item {
			background-color: #fff;
			border-radius: 8px;
			padding: 15px;
			margin-bottom: 10px;

			.info-row {
				display: flex;
				margin-bottom: 8px;

				&:last-child {
					margin-bottom: 0;
				}

				.label {
					width: 80px;
					color: #666;
					font-size: 14px;
				}

				.value {
					flex: 1;
					color: #333;
					font-size: 14px;
				}
			}
		}
	}
</style>